package tvv.levelup.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import tvv.levelup.models.Pet;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by VLAD on 02.09.2014.
 */
@Repository
public class PetDao implements IPetDao {
    private JdbcTemplate jdbcTemplate;


    @Autowired
    public PetDao(DriverManagerDataSource dataSource) {
        jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public Pet getPetById(int id) {
        String query = "SELECT * FROM prt_db.pet where id = ?";

        Pet pet = jdbcTemplate.queryForObject(query,
                new Object[]{new Integer(id)},
                new RowMapper<Pet>() {
                    @Override
                    public Pet mapRow(ResultSet resultSet, int i) throws SQLException {
                        Pet p = new Pet();
                        p.setId(resultSet.getInt("id"));
                        p.setMood(resultSet.getInt("mood"));
                        return p;

                    }
                });
        return pet;
    }

    @Override
    public void savePet(Pet pet) {
        String query = "INSERT INTO pet (id, mood) VALUES (?, ?)";
        jdbcTemplate.update(query,
                pet.getId(),
                pet.getMood());
    }

    @Override
    public void deletePet(Pet pet) {

        String query = "DELETE FROM pet WHERE id = ?";
        jdbcTemplate.update(query, pet.getId());

    }

    @Override
    public int getActualPetId() {
        return jdbcTemplate.queryForInt("SELECT max(id) FROM prt_db.pet") + 1;
    }


}
